<?php

class OrderController extends Controller {
    /**
     * 
     */
    public function filters() {
        parent::filters();
        $this->menu_backend = "#ban_hang";
    }

    /**
     * 
     */
    public function actionIndex() {
        $criteria = new CDbCriteria();
        $orderSearch = new OrderSearch();
        $count = Order::model()->count($criteria);
        if(isset($_GET['OrderSearch'])){
            $orderSearch->attributes = $_GET['OrderSearch'];
            $params = array();
            if(strlen($_GET['OrderSearch']['order_id']) > 0){
                $criteria->addCondition('order_id = :order_id');
                $params[':order_id'] = $_GET['OrderSearch']['order_id'];
            }
            if(strlen($_GET['OrderSearch']['payment_name']) > 0){
                $criteria->addCondition('payment_name like :payment_name');
                $params[':payment_name'] = "%".$_GET['OrderSearch']['payment_name']."%";
            }
            if(strlen($_GET['OrderSearch']['payment_phone']) > 0){
                $criteria->addCondition('payment_phone like :payment_phone');
                $params[':payment_phone'] = "%".$_GET['OrderSearch']['payment_phone']."%";
            }
            if(strlen($_GET['OrderSearch']['status']) > 0 && $_GET['OrderSearch']['status'] > 0){
                $criteria->addCondition('status = :status');
                $params[':status'] = $_GET['OrderSearch']['status'];
            }
            
            
            $criteria->params = $params;
        }
        $pages = new CPagination($count);
        $pages->pageSize = 10;
        $pages->applyLimit($criteria);
        $orders = Order::model()->findAll($criteria);
        $arrayStatus = array(
                    1 => 'chờ xử lý',
                    2 => 'đang giao hàng',
                    3 => 'hoàn tất đơn hàng'
                );
        $this->render('index', array('arrayStatus'=>$arrayStatus,'orders' => $orders,'orderSearch' => $orderSearch,'pages' => $pages));
    }
    
    /**
     * 
     */
    public function actionView($id = null){
        if($id != null){
            $order = Order::model()->findByPk($id);
            if($order != null){
                if(isset($_REQUEST['status_update'])){
                    $order->status = $_REQUEST['status_update'];
                    if($order->save()){
                        Yii::app()->user->setFlash('success', "Cập nhật đơn hàng thành công");
                    }
                }
                $arrayStatus = array(
                    1 => 'chờ xử lý',
                    2 => 'đang giao hàng',
                    3 => 'hoàn tất đơn hàng'
                );
                $this->render('view', array('order' => $order,'arrayStatus'=>$arrayStatus));
            }else{
                throw new CHttpException(404, 'Đơn hàng không được tìm thấy.');
            }
        }else{
            throw new CHttpException(404, 'không có mã đơn hàng');
        }
    }

}